package resources

import (
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
	"strings"
)

type UploadRequest struct {
	Path string `form:"path" validate:"required" binding:"required"` // 路径
}

type UploadResponse struct {
	Path string `json:"path" validate:"required"` // 文件的绝对路径
}

func (cls *Resources) Upload(c *gin.Context) (int, any, error) {
	var body = UploadRequest{}
	if err := c.ShouldBind(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	f, err := c.FormFile("file")
	if nil != err {
		return response.InvalidRequest, nil, errors.New("未上传文件")
	}

	reader, err := f.Open()
	if nil != err {
		return response.InvalidRequest, nil, errors.New("打开文件失败")
	}

	defer func() {
		if err := reader.Close(); nil != err {
			logger.GetLogger().Sugar().Errorf("关闭文件失败: %s", err)
		}
	}()

	// 创建目录
	if err := cls.resources.MakeDir(strings.Split(body.Path, "/")); nil != err {
		return response.Unknown, nil, err
	}

	// 保存文件
	if err := cls.resources.SaveFile(append(strings.Split(body.Path, "/"), f.Filename), reader); nil != err {
		return response.Unknown, nil, err
	}

	path, err := cls.resources.AbsFilepath(strings.Split(body.Path, "/"), f.Filename)
	if nil != err {
		return response.Unknown, nil, err
	}

	return response.Ok, UploadResponse{Path: path}, nil
}
